﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.Helper;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Net;

namespace SinaImgUpload.SainTool.LocalTool
{
    internal class ClearWithPixivExclude
    {
        /// <summary>
        /// 处理黑名单文件的路径
        /// </summary>
        public static string PixivBanIdPath = StaticValue.TempPath + "PixivBanId.txt";

        /// <summary>
        /// P站通过鉴别的列表
        /// </summary>
        public static string PixivAdoptIdPath = StaticValue.TempPath + "PixivDAdoptId.txt";

        /// <summary>
        /// 读取的黑名单缓存
        /// </summary>
        public static List<string> PixivBanIdList = FileHelper.ReadAllLine(PixivBanIdPath);

        /// <summary>
        /// 读取已通过词库
        /// </summary>
        public static List<string> PixivAdoptList = FileHelper.ReadAllLine(PixivAdoptIdPath);

        /// <summary>
        /// 处理单个列表文件
        /// </summary>
        /// <param name="XmlFloderPath"></param>
        /// <param name="ExcludeKeyFile"></param>
        public void HandleXmlFloder(string XmlFloderPath, string ExcludeKeyFile)
        {
            List<string> FoloderList = FloderNameHelper.GetFullFileNameList(XmlFloderPath, "*.lst");
            List<string> ExcludeList = FileHelper.ReadAllLine(ExcludeKeyFile);
            foreach (string line in FoloderList)
            {
                Console.WriteLine(line);
                HandleXml(line, ExcludeList);
            }
        }

        /// <summary>
        /// 处理单个列表文件
        /// </summary>
        /// <param name="XmlFilePath"></param>
        /// <param name="ExcludeKeyFile"></param>
        public void HandleXml(string XmlFilePath, string ExcludeKeyFile)
        {
            //  HandleXml(XmlFilePath, FileHelper.ReadAllLine(ExcludeKeyFile));
            HandleXml(XmlFilePath, ExcludeKeyFile);
        }

        /// <summary>
        /// 处理单个文件的情况
        /// </summary>
        /// <param name="XmlFilePath"></param>
        /// <param name="ExcludeKeyList"></param>
        public void HandleXml(string XmlFilePath, List<string> ExcludeKeyList)
        {
            if (XmlFilePath == "")
                return;
            List<string> ImgList = HtmlHelper.GetHtmlValueList(FileHelper.ReadAllText(XmlFilePath), "//bed");
            List<string> TempImgList = new List<string>();
            foreach (String Line in ImgList)
            {
                string PixivLink = HtmlHelper.GetFirstText(Line, "//original");
                if (PixivLink == "")
                    continue;

                if (GetImgJumpFlag(PixivLink, ExcludeKeyList))
                    continue;
                TempImgList.Add(Line);
            }
            if (TempImgList.Count > 0)
                FileHelper.WriteList(FileNameHelper.CreateFileNameWithChildFloder(XmlFilePath, "_已处理"), TempImgList);
            else
                Console.WriteLine("全部未通过，不写入资源。");
        }

        /// <summary>
        /// 获取图片是否触发跳出，触发返回true
        /// </summary>
        /// <param name="PixivLink"></param>
        /// <returns></returns>
        private bool GetImgJumpFlag(string PixivLink, List<string> ExcludeKeyList)
        {
            string PixivId = TextHelper.RegexText(PixivLink, "/[0-9]{1,}_p");
            PixivId = TextHelper.ReplaceTextEnhance(PixivId, "(/|_p)", "");
            if (ReadOldLogJump(PixivId) || PixivId == "")
            {
                Console.WriteLine("读取本地记录，{0}存在，跳出。", PixivId);
                return true;
            }
            string API = "https://www.pixiv.net/ajax/user/24517/illusts?ids[0]=" + PixivId;
            WebHeaderCollection webHeaderCollection = WebHelper.PcWebHeader();
            webHeaderCollection.Add("Cookie: PHPSESSID=24587510_656bbb6e15136786f1bfeddfd03043a4; p_ab_id=4; p_ab_id_2=5; device_token=6d750eb0d979c20914dc5c850a4b4596; privacy_policy_agreement=1; c_type=22; a_type=0; b_type=1; d_type=1; module_orders_mypage=%5B%7B%22name%22%3A%22sketch_live%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22tag_follow%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22recommended_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22showcase%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22everyone_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22following_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22mypixiv_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22fanbox%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22featured_tags%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22contests%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22user_events%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22sensei_courses%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22spotlight%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22booth_follow_items%22%2C%22visible%22%3Atrue%7D%5D; yuid=KJECMnI37; login_ever=yes; tag_view_ranking=BU9SQkS-zU~y8GNntYHsi~_hSAdpN9rx~UX647z2Emo~WcTW9TCOx9~w-HSw8XliK~2fTx4fs8a8~XMeKnjoeVa~zlLh7B6pY8~OXID0M1Z5f~8jLEb-nz4N~2mHMFxA0cV~xZ6jtQjaj9~RTJMXD26Ak~Lt-oEicbBr~Ac_mADAVwx~4gzX-RNalt~BtXd1-LPRH~lxfrUKMf9f~Ie2c51_4Sp~pusqGCt8hY~k3L7pRbDNW~NpsIVvS-GF~q3eUobDMJW~QR9TTbOVZg~RcahSSzeRf~t4pUmgSzLU~P35cc-gV8H~2GVngxkxTb~U1IgaHEng2~lvPPee_RhW~PHUvS4W3aB~tlI9YiBhjp~SdTBEkQ41U~5Aw24FdbaX~kP7msdIeEU~ImzhrGsTUJ~qcyZtLflOe~uGQeWvelyQ~g46N4P5qOY~N8DMNU5sJM~YKAliF34Ha~EDqBY8bzXR~OZbzcrhaSe~oJAJo4VO5E~1LN8nwTqf_~hM1TCn1fqR~eUGxaXhDG_~9E_tEha2Kz~j2lJ8_51Vq~ohyEOOtuTb~tliJ56NT0b~dkp33KDmQM~2wNJ4E2Ez3~EuzYuWvJQm~9sZnorvHdn~VH8uND52Y3~plmutDYyvJ~Ib2sJgOm0e~_07xHHF0DK~ZJNZbYl3mo~CpxCjgnG0-~rz5wFtbyrJ~8Ed0zPBVda~bXMh6mBhl8~MITa5rRYPk~roGVNL55qj~MYYScn4S_T~BRv3eEWFqu~eE5ORV6KVQ~7YjK_c_EhV~qG3Gvz7IsI~BQv9ZOKrJ7~MB3R8aRg8h~TqpjDOGeaj~uv3ZYiBpXA~nRD8dg8GXF~T2ZL2YdFPF~B7-UJhFS_B~ac2E3diIZ2~Ee-SCiu-RT~lz_wwsv1W1~m3g5PuSn7b~dqqWNpq7ul~3T_AQ0B2Q3~uXVJGoIMP_~ZBoVMjk2oM~k1zILvJ0is~Y1xsKC1Dhb~4Ew9pzGr3u~58v2dGDkfe~pH6s5n7DaD~1TmQ6hDdv7~AbZ3Nbb93k~cdUSwWV8mz~YAZ8GpVIK5; is_sensei_service_user=1");
            String Shtml = WebHelper.HttpGet(API, webHeaderCollection);
            Shtml = TextHelper.RegexText(Shtml, "\"tags\":\\[.*?\\]")

                + TextHelper.RegexText(Shtml, ",\"userId\":\"[0-9]{0,}\"");

            try
            {
                if (Shtml == "")
                    return true;
                Shtml = "{" + Shtml + "}";
                Console.WriteLine(Shtml);
                PixivArtInfo pixivArtInfo = JsonConvert.DeserializeObject<PixivArtInfo>(Shtml);
                pixivArtInfo.tags.Add(pixivArtInfo.userId);
                bool ExitFlag = ListHelper.CompareRepetition(pixivArtInfo.tags, ExcludeKeyList);

                if (!ExitFlag)
                {
                    Console.WriteLine("验证通过");
                    return false;
                }
                FileHelper.AppendText(PixivBanIdPath, PixivId);
                PixivBanIdList.Add(PixivId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("初始化JSON失败");
                PrintLog.Log(ex.Message);
            }
            return true;
        }

        /// <summary>
        /// 判断是否在黑名单列表中
        /// </summary>
        /// <param name="PixivId"></param>
        /// <returns></returns>
        private bool ReadOldLogJump(string PixivId)
        {
            return PixivBanIdList.Contains(PixivId);
        }

        public class PixivArtInfo
        {
            /// <summary>
            ///标签列表
            /// </summary>
            public List<string> tags { get; set; }

            /// <summary>
            /// 用户ID
            /// </summary>
            public string userId { get; set; }
        }
    }
}